/*
*Set global variables
*/
var map;							
var markers;
var eventsArray; 					//Global array for events
var eventsStore; 					//Store for event data loaded in Grid
var eventVisibility;				//Global variable for event visibility in insertEventPanel
var lineChartStore;					//Store for line chart (amout of events per month)
var lineChartArray;
var pieChartStore;					//Store for pie chart (amout of events per category)
var pieChartArray;
var editEventVisibility;			//Global variable for event visibility in editEventPanel
var editableEventsStore;

/*
 * This function is being called when the website is being loaded. It sets the the layout 
 * and the behavior of the the components.
 */ 
Ext.onReady(function() {	
	map = new OpenLayers.Map();									//Create map instance

	var osmLayer = new OpenLayers.Layer.OSM("OSM");				//Create OSM layer
	markers = new OpenLayers.Layer.Markers("Markers");			//Create markers layer

	map.addLayers([osmLayer, markers]);							//Add the created layers
	    
    /*
     * Handler for the click event: 
     *  - get coordinates from map at the clicked position
     *  - reverse geocode the coordinates
     *  - safe result in the newEventPanel 
	*/
	OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
		defaultHandlerOptions: {
		   "single": true,
		   "double": false,
		   "pixelTolerance": 0,
		   "stopSingle": false,
		   "stopDouble": false
		},
		
		initialize: function(options){
			this.handlerOptions = OpenLayers.Util.extend(
					this.defaultHandlerOptions
			);
		    OpenLayers.Control.prototype.initialize.apply(
		    		this, arguments
		    ); 
		    this.handler = new OpenLayers.Handler.Click(
		    		this, {
		    			"click": this.trigger
		    		}, this.handlerOptions
		    );
		}, 
	
	   trigger: function(e){
  		    var lonlat = map.getLonLatFromPixel(e.xy).transform(
		  		map.getProjectionObject(), 						//Transform from 'Spherical Mercator Projection' (EPSG:900913)
		  		new OpenLayers.Projection("EPSG:4326") 			//To WGS 1984
		    );
	   
	   		Ext.getCmp("lat").setValue(lonlat.lat);				//Set clicked coordinates in the newEventPanel
		   	Ext.getCmp("long").setValue(lonlat.lon);
		   	revGeocode(lonlat.lat, lonlat.lon);					//Call revGeocode function		
	   }
	});
	
	var click = new OpenLayers.Control.Click();					//Create OpenLayers control element to the click
    map.addControl(click);										//Add the control element to the map
    click.activate();											//Activate the control element
    
    var mapPanel = new GeoExt.MapPanel({						//Create map panel
        title: "Karte",											//Set map title
        region: "center",										//Set the position of the map in the ExtJS border layout (reference for the viewport)
        map: map,												//Link the created map to the mapPanel
        center: new OpenLayers.LonLat(13.261764, 53.556218)
    		.transform(
    			  new OpenLayers.Projection("EPSG:4326"), 		//Transform from WGS 1984
        		  map.getProjectionObject() 					//To 'Spherical Mercator Projection' (EPSG:900913)
       		),
        zoom: 10												//Set basic zoomlevel of the map
    });
    
    var headerGraphic = new Ext.BoxComponent({					//Set up the header graphic
    	cls:"headerGraphic", 									//Set CSS reference name
    	autoEl: {tag: "img", src: "../img/headerGraphic.png"}		
    });
    
    var logoutPanel = new Ext.FormPanel({						//Create logout panel
    	baseCls: "logoutPanel",									//Set CSS reference name
	    labelWidth: 130,										//Set basic width for the labels
	    defaults: {width: 80},									//Set basic width of the labels
	    items :[
	            {
	            	xtype: "button",							
			        cls: "logoutPanelButton",					//CSS reference
			        fieldLabel: "Benutzer abmelden",			//Set the label of the button
			        text: "Logout",								//Set the button text
			        handler: function(){						//Add handler to the button
			        	logoutRequest();						//Trigger the logout function
			        }
	            }
	    ]	     
    });
    
	/*
	 * Validate date from the filterPanel
	 * Check whether the end date is before the start date and lock dates in the calendar
	 */
    Ext.apply(Ext.form.VTypes, {
    	daterange : function(val, field) {
            var date = field.parseDate(val);

            if(!date){
                return false;
            }
            if (field.startDateField) {
                var start = Ext.getCmp(field.startDateField);
                if (!start.maxValue || (date.getTime() != start.maxValue.getTime())) {
                    start.setMaxValue(date);
                    start.validate();
                }
            }
            else if (field.endDateField) {
                var end = Ext.getCmp(field.endDateField);
                if (!end.minValue || (date.getTime() != end.minValue.getTime())) {
                    end.setMinValue(date);
                    end.validate();
                }
            }
    	}
    });
        
    var allocatedEventCategoriesStore = new Ext.data.XmlStore({					//Get event categories from MySQL-DB and store
    	autoLoad: true,
	    url: "../php/phpsql_getAllocatedEventCategories.php",	
	    fields: ["name"],
	    record: "category"
	});
    
    var osLengthStore = new Ext.data.SimpleStore({								//Create store for the orbiting search in the filter panel   
        fields: ['value'],
        data: [[5],[10],[15],[20],[25],[30],[35],[40],[45],[50]],				//Set distance options
        autoLoad: true
    });

	var allocatedEventTownsPLZStore = new Ext.data.XmlStore({					//Get event towns from MySQL-DB and store them
    	autoLoad: true,
	    url: "../php/phpsql_getAllocatedEventTownsPLZ.php",
	    fields: ["name"],
	    record: "town"
	});
	
	var filterPanel = new Ext.FormPanel({										//Create panel for the filters
		frame: true,															//Disable frame
		cls: "filterPanel",														//Set the CSS reference name	
		items: [
		        	{
						layout: "column",						//Add filters to a column layout with 2 columns 
						items: [
						        	{ 											//Column #1
								        columnWidth: .50,						//Width of the columns = 50%
								        autoScroll:true,										
										layout: "form",
										labelWidth: 80,							//Set basic width for the labels								
										defaults: {width: 180},					//Set basic width of the labels
										items: [
										        	{
										        		xtype: "datefield",	
										        		format: "Y-m-d",		//Set date format
										        		fieldLabel: "Start",	//Set label	of the field					
										        		id: "startdt",			//Set id
										        		vtype: "daterange",		//Set reference for the function which validates the correct daterange
										        		endDateField: "enddt" 	//Set the id of the end date field
													},
													{
														xtype: "datefield",
														format: "Y-m-d",
														fieldLabel: "Ende",							
														id: "enddt",
														vtype: "daterange",
														startDateField: "startdt" 	//Set the id of the end date field
													},
													{
														xtype: "combo",
														mode: "local",				//Loads local data
														typeAhead: true,			//Allows to complete the results automatically when you type into the field
														triggerAction: "all",		//Allow all triggers
														fieldLabel: "Typ",			//Set label	of the field	
														id: "eventType",			//Set id
														displayField: "name",		//Set the displayed field of the combo box
														valueField: "name",			//Set the actual value field of the combo box
														store: allocatedEventCategoriesStore		//Set the store of the combo box
													},
													{
														xtype: "button",
														cls:"filterPanelButton",					//Set CSS reference name
														text: "Veranstaltungen suchen",				//Set label	of the button
														id:"filterPanelButton",
														/*
														 * 	Create handler for the button
														 *  If handler is triggered get all filter parameters and call getEvents function
														 */
														handler: function(){
															//Regular expression for filter elements
															var townEmptyExpression=/^$/;
															var townExpression=/(^(.)+, [0-9]{5}$)/;
															var eventTypeExpression=/(^$|^\w+$)/;
															var dateExpression=/(^$|^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$)/;
															var eventRadiusExpression=/(^$|^[0-9]+$)/;
															if(dateExpression.test(Ext.get("startdt").getValue())==false){
																alert("Bitte Startdatum überprüfen!");
																}else{
																var startdt = Ext.get("startdt").getValue();
															}
																
															if(dateExpression.test(Ext.get("enddt").getValue())==false){
																alert("Bitte Enddatum überprüfen!");
																}else{
																var enddt = Ext.get("enddt").getValue();
															}
															
															if(eventRadiusExpression.test(Ext.get("osRadius").getValue())==false){
																alert("Bitte Radius überprüfen!");
																}else{
																var eventRadius = Ext.getCmp("osRadius").getValue();
															}
															
															if(dateExpression.test(Ext.get("startdt").getValue())==false){
																alert("Bitte Startdatum überprüfen!");
																}else{
																var startdt = Ext.get("startdt").getValue();
															}	
															
															if(townEmptyExpression.test(Ext.get("osCenter").getValue())==false){
																if(townExpression.test(Ext.get("osCenter").getValue())==false){
																	alert("Bitte vordefinierte Städte auswählen");			
																	}else{
																	var city=Ext.get("osCenter").getValue()																	
																	}		
															}
															
															if(eventTypeExpression.test(Ext.get("eventType").getValue())==false){
																	alert("Bitte Event Kategorie überprüfen!");			
																	}else{
																	var eventType = Ext.get("eventType").getValue();
															}	
															
															getEvents(startdt, enddt, eventType, eventRadius, city);																													
														}
													}
										] //Close items for first column
						        	},
									{
						        		columnWidth: .50,
						        		labelWidth: 80,							//Set basic width for the labels								
										defaults: {width: 180},					//Set basic width of the labels
						        		autoScroll:true,
										
						        		layout: "form",
						        		items: [
						        		        	{
														xtype: "combo",
														mode: "local",								//Loads local data						
														triggerAction: "all",						//Allow all triggers
														id: "osCenter",								//Set id
														fieldLabel: "Ort",							//Set label	of the field
														displayField: "name",						//Set the displayed field of the combo box
														valueField: "name",							//Set the actual value field of the combo box
														store: allocatedEventTownsPLZStore			//Set the store of the combo box
													
						        		        	},
													{	
						        		        		xtype: "combo",								
						        		        		mode: "local",								//Loads local data		
						        		        		triggerAction: "all",						//Allow all triggers
						        		        		fieldLabel: "Radius",						//Set label	of the field
						        		        		id: "osRadius",								//Set id
						        		        		displayField: "value",						//Set the displayed field of the combo box
						        		        		valueField: "value",						//Set the actual value field of the combo box
						        		        		store: osLengthStore						//Set the store of the combo box
													}
										] //Close items for second column
									}
						]
		        	}
		]
	});


	
   eventsStore = new Ext.data.ArrayStore({					//Create data store for the events stored in eventsArray
        fields: [											//Define the fields of the store
           {name: "name"},
           {name: "description"},
           {name: "eventsCategory"},
           {name: "fee"},
           {name: "date"},
           {name: "street"},
           {name: "nr"},
           {name: "plz"},
           {name: "town"}
        ]
    });
     
    var eventsGrid = new Ext.grid.GridPanel({				//Create eventsGrid
    	store: eventsStore,									//Set the store of the grid
        viewConfig: {										//Set grid = 100% of the div-container
			forceFit: true
		},
		autoHeight: true,									//Allow multiple rows; Height is being calculated automatically 
		columns: [											//Define the columns of the grid
		            {
		            	id       :"eventsName",				//Set the id of the column
		                header   : "Name", 					//Set the column header text
		                width    : 100, 					//Set default width of the column
		                sortable : true, 					//Allow the column to be sortable
		                dataIndex: "name"					//Set the reference for the eventsStore 
		            },
		            {
		                id       :"eventsCategory",
		                header   : "Typ",
		                sortable : true, 
		                width    : 60,  
		                dataIndex: "eventsCategory"
		            },
		            {
		                id       :"eventsDate",
		                header   : "Datum/Uhrzeit",
		                sortable : true, 
		                width    : 115,  
		                dataIndex: "date"
		            },
		            {
		                id       :"eventsStreet",
		                header   : "Straße",
		                width    : 100,  
		                dataIndex: "street"
		            },
		            {
		                id       :"eventsNr",
		                header   : "Nr",
		                width    : 30,  
		                dataIndex: "nr"
		            },
		            {
		                id       : "eventsTown",
		                header   : "Ort",
		                width    : 100,  
		                dataIndex: "town"
		            },
		            {
			            id		 : "eventsDescription",
			            header	 : "Beschreibung",
			            width    : 75,  
			            /*
			             * The renderer generates an link to the eventDescription page and adds the the event attributes as GET-parameters
			             */
			            renderer: function (val, meta, record){
			            	var url = "./eventDescription.php?";									//Url to the eventDescription page
			            	
			            	//Set GET-parameters

			            	var name = "name="+record.data.name;	
			            	var eventsCategory = "&eventsCategory="+record.data.eventsCategory;
			            	var date = "&date="+record.data.date;
			            	var street = "&street="+record.data.street;
			            	var nr = "&nr="+record.data.nr;
			            	var town = "&town="+record.data.town;
			            	
			            	var getParameters = name+eventsCategory+date+street+nr+town;			//Combined GET-parameters
			            	return "<a href='"+url+getParameters+"' target='_blank'>LINK</a>";		//Create the link 
			            }
		            }            
        ]
    });
    
    var publicPanel = new Ext.TabPanel({				//Create tab panel for public elements
    	region: "west",									//Set the position of the map in the ExtJS border layout (reference for the viewport)
    	split: true,									//Allow the sidebar have a flexible position
		collapsible: true,								//Allow sidebar to be collapsible
		collapseMode: "mini",							
        autoScroll: true,								
		cls: "publicPanel",								//Set CSS reference name
	    activeTab: 0,									//Set default tab
	    items: [
			    	mapPanel,							//Add the mapPanel
			    	{
			    		title: "Filter",
			    		autoScroll: true,								
			    		items:[
			    			filterPanel,				//Add the filterPanel		
			    			eventsGrid					//Add the gridPanel
			    		]
			    	}
	    ]
	});	
	
    var allEventCategoriesStore = new Ext.data.XmlStore({		//Get all categories from MySQL-DB and store them
    	autoLoad: true,
	    url: "../php/phpsql_getAllEventCategories.php",
	    fields: ["name","idEventCategories"],
	    record: "category"
	});
	
	
	
	var culturalUserStore = new Ext.data.XmlStore({				//Get all cultural user
    	autoLoad: true,
		url: "../php/phpsql_getCulturalUser.php",
	    fields: ["iduser","name"],
	    record: "user"
	});
	
	var eventCategorieElement=new Ext.ux.form.CheckboxCombo({  	//build combo box with checkbox for multiple category selection
                width: 250,
                mode: "local",
				multiSelect: true,
				id: "allEventCategories",
				fieldLabel: "Kategorien",
                store: allEventCategoriesStore,
                valueField: "idEventCategories",
                displayField: "name",
                allowBlank: false
        });
	
	var newEventPanel = new Ext.FormPanel({						//Create panel to define new events
		baseCls: "newEventPanel",	
		autoScroll:true,		
		defaultType: "textfield",
		labelWidth: 160,											
		defaults: {width: 250},	
		items :[
					{	
						fieldLabel: "Name der Veranstaltung *",
						id: "name"			
					},
					{
						xtype: "textarea",
						fieldLabel: "Beschreibung der Veranstaltung",
						id: "description"				
					},
					{
						fieldLabel: "Eintrittskosten",
						id: "fee"				
					},
					{
						fieldLabel: "Lat",
						id: "lat",
						cls:"newEventPanelLatLongField",
						readOnly: true
					},
					{
						fieldLabel: "Long",
						id: "long",
						cls:"newEventPanelLatLongField",
						readOnly: true								
					},
					{
						fieldLabel: "Stadt *",
						id: "town"								
					},
					{
						fieldLabel: "PLZ *",
						id: "plz"									
					},
					{
						fieldLabel: "Straße",
						id: "street"									
					},
					{
						fieldLabel: "Haus Nr",
						id: "nr"									
					},
					{
						xtype: "radiogroup",
						fieldLabel: "Sichtbar",
						id: "visibility",
						items: [
							{
							  boxLabel: 'Ja',
							  name: 'radio',
							  inputValue: 1,
							  listeners: {
								  change : function(){ 
										 if (this.getValue()) {
											eventVisibility=1; 		//Set Global variable for visibiltity of an event 1(visible) if checked
										 }
									}
								}
							},
							{
							  boxLabel: 'Nein',
							  name: 'radio',
							  inputValue: 0,
							  listeners: {
								  change : function(){ 
										 if (this.getValue()) {
											eventVisibility=0; 		//Set Global variable for visibiltity of an event 0 (invisible) if checked 
										 }
									}
								}
							}]
						
											
					},
					{
						xtype: "datefield",
						format: "Y-m-d",
					  	fieldLabel: "Datum der Veranstaltung *",												
					  	vtype: "daterange",
					  	id: "date"						
					},
					{
						xtype: "timefield",
						id: "time",
						format: "H:i",
						fieldLabel: "Start Zeit *",
						altFormats:"H:i"	
					},
					[eventCategorieElement],
					{
						fieldLabel: "Website",
						id: "link"									
					},
					
					/*
					 * This area is still under construction future students will have to keep on working on this part
					 */
					/*{
	                    xtype: "fileuploadfield",
	                    id: "newEventUploadField",
	                    fieldLabel: "Datei",
	   					buttonText: "Duchsuchen..."
	                },*/
					
	                {
						xtype: "combo",
						mode: "local",										//Loads local data
						typeAhead: true,									//Completes the results automatically
						triggerAction: "all",
						fieldLabel: "Kulturnutzer",
						id: "culturalUser",
						hiddenName: "culturalUser",
						displayField: "name",
						valueField: "iduser",
						store: culturalUserStore
					},
					{
						fieldLabel: "Schlagworte",
						id: "keywords"										
					},
					{
						xtype: "button",
						cls:"newEventPanelButton",
						text: "Veranstaltung entragen",
						/*
						 * Create handler for the button
						 * Call validateNewEvent function if triggerd
						 */
						handler: function(){
						validateNewEvent(this);						
						}
				}
					
		]
	});
	
	lineChartStore = new Ext.data.ArrayStore({					//Create data store for the statistic information stored in statisticsArray
        fields: [												//Define the fields of the store
           {name: "month"},
           {name: "amount"},
        ]
    });

	getLineChartStatistics();									//Call the statistic informations from the DB
	
	//Linechart statistics panel
	var lineChartStatisticsPanel = new Ext.Panel({
        height: 200,
        title: "Veranstaltungsanzahl",
        frame:true,
        layout:"fit",
        handler: function(){},
        items: {
            xtype: "linechart",
            store: lineChartStore,
            url: "../js/lib/ExtJS-3.3.1/resources/charts.swf",
            xField: "month",
            yField: "amount"
        }
    });
    
    pieChartStore = new Ext.data.ArrayStore({					//Create data store for the statistic information stored in statisticsArray
        fields: [												//Define the fields of the store
           {name: "eventcategory"},
           {name: "amount"},
        ]
    });
	
	getPieChartStatistics();									//Call the statistic informations from the DB
	
	//Piechart statistic panel
    var pieChartStatisticsPanel = new Ext.Panel({
        height: 250,
        title: "Kategorieübersicht",
        items: {
            store: pieChartStore,
            xtype: "piechart",
            dataField: "amount",
            categoryField: "eventcategory",
            url: "../js/lib/ExtJS-3.3.1/resources/charts.swf",
        	extraStyle:
            {
                legend:
                {
                    display: 'bottom',
                    padding: 5,
                    font:
                    {
                        family: 'Tahoma',
                        size: 13
                    }
                }
            }
        }
    });
	
	 editableEventsStore = new Ext.data.XmlStore({		//Get all events related to user from Store
    	autoLoad: true,
	    url: "../php/phpsql_getEditableEvents.php",
	    fields: ["idevent","name"],
	    record: "event"
	});
	

	
	var editEventCategorieElement=new Ext.ux.form.CheckboxCombo({  	//build combo box with checkbox for multiple category selection
                width: 250,
                mode: "local",
				multiSelect: true,
				id: "editCategories",
				fieldLabel: "Kategorien",
                store: allEventCategoriesStore,
                valueField: "idEventCategories",
                displayField: "name",
                allowBlank: false
        });
	
	var editEventPanel = new Ext.FormPanel({						//Create panel to edit events
		baseCls: "editEventPanel",	
		autoScroll:true,		
		defaultType: "textfield",
		labelWidth: 160,											
		defaults: {width: 250},
		items :[
					{	
						xtype:"combo",
						mode: "local",
						
						typeAhead: true,									
						triggerAction: "all",
						fieldLabel: "Veranstaltung auswählen",
						id: "editableEvent",
						store: editableEventsStore,
						displayField: "name",
						valueField: "idevent",
						enableKeyNav: false,
							listeners:{		
								select: function(combo,record,index){								//Trigger on select to get information of an event
								clearEditEventFormular();   										//Clear all editEventPanel elements
								getEventInformation(Ext.getCmp("editableEvent").getValue(),this);	//Get event information
								}
							}
					},
					{
						xtype: "button",
						cls:"newEventPanelButton",
						text: "Veranstaltung löschen",
						/*
						 * Create handler for the button
						 * delete Event if selected
						 */
					handler: function(){
							var noEmptyFieldExpression = /^[^"';]+$/;
							if (noEmptyFieldExpression.test(Ext.get("editableEvent").getValue())==false ){
								alert("Eine Veranstaltung zum bearbeiten muss ausgewählt werden");
							}
							else{							
								deleteEvent(Ext.getCmp("editableEvent").getValue());				//Delete event
								
							}
						}
					},
					{	
						fieldLabel: "Name der Veranstaltung *",
						id: "editName"			
					},
					{
						xtype: "textarea",
						fieldLabel: "Beschreibung der Veranstaltung",
						id: "editDescription"				
					},
					{
						fieldLabel: "Eintrittskosten",
						id: "editFee"				
					},
					{
						fieldLabel: "Lat",
						id: "editLat",
						cls:"newEventPanelLatLongField",
						readOnly: true
					},
					{
						fieldLabel: "Long",
						id: "editLong",
						cls:"newEventPanelLatLongField",
						readOnly: true								
					},
					{
						fieldLabel: "Stadt *",
						id: "editTown"								
					},
					{
						fieldLabel: "PLZ *",
						id: "editPlz"									
					},
					{
						fieldLabel: "Straße",
						id: "editStreet"									
					},
					{
						fieldLabel: "Haus Nr",
						id: "editNr"									
					},
					{
						xtype: "radiogroup",
						fieldLabel: "Sichtbar",
						id: "editVisibility",
						items: [
							{
							  boxLabel: 'Ja',
							  name: 'radio',
							  inputValue: 1,
							  id: "editVisibilityYes",
							  listeners: {
								  change : function(){ 
										 if (this.getValue()) { // checked.
											editEventVisibility=1; // or "no" 
										 }
									}
								}
							},
							{
							  boxLabel: 'Nein',
							  name: 'radio',
							  inputValue: 0,
							  id: "editVisibilityNo",
							  listeners: {
								  change : function(){ 
										 if (this.getValue()) { // checked.
											editEventVisibility=0; // or "no" 
										 }
									}
								}
							}]
						
											
					},
					{
						xtype: "datefield",
						format: "Y-m-d",
					  	fieldLabel: "Datum der Veranstaltung *",												
					  	vtype: "daterange",
					  	id: "editDate"						
					},
					{
						xtype: "timefield",
						id: "editTime",
						format: "H:i",
						fieldLabel: "Start Zeit *",
						altFormats:"H:i"	
					},
					[editEventCategorieElement],
					{
						fieldLabel: "Website",
						id: "editLink"									
					},
					
					/*
					 * This area is still under construction future students will have to keep on working on this part
					 */
					/*{
	                    xtype: "fileuploadfield",
	                    id: "newEventUploadField",
	                    fieldLabel: "Datei",
	   					buttonText: "Duchsuchen..."
	                },*/
   
					{
						fieldLabel: "Schlagworte",
						id: "editKeywords"										
					},
					{
						xtype: "button",
						cls:"newEventPanelButton",
						text: "Bearbeitung abschließen",
						/*
						 * Create handler for the button
						 * delete Event if selected
						 */
					handler: function(){
							var noEmptyFieldExpression = /^[^"';]+$/;
							if (noEmptyFieldExpression.test(Ext.get("editableEvent").getValue())==false ){
								alert("Eine Veranstaltung zum bearbeiten muss ausgewählt werden");
							}
							else{
								/*
								* here should be regular expressions
								*/

								dateNew=Ext.get("editDate").getValue().concat(" ");
								
								editEvent(Ext.getCmp("editableEvent").getValue(),Ext.get("editName").getValue(),Ext.get("editDescription").getValue(),Ext.get("editFee").getValue(),Ext.get("editLat").getValue(),
								Ext.get("editLong").getValue(),Ext.get("editTown").getValue(),Ext.get("editPlz").getValue(),Ext.get("editStreet").getValue(),Ext.get("editNr").getValue(),
								editEventVisibility,dateNew.concat(Ext.get("editTime").getValue()), Ext.get("editCategories").getValue(),Ext.get("editLink").getValue(),
								Ext.get("editKeywords").getValue());
								
							}
						}
					}
				]
	});
					
    
    var administrationPanel = new Ext.TabPanel({				//Create tab panel for admin functions
	    region: "center",										//Set the position of the map in the ExtJS border layout (reference for the viewport)
	    activeTab: 0,
	    items: [
				    {
						title: "Neue Veranstaltung",
						layout: "fit",
						items: [
							newEventPanel						//Add the newEventPanel	
						]
					},
					{
						title: "Veranstaltung bearbeiten",
						layout: "fit",
						items: [
							editEventPanel						//Add the newEventPanel	
						]
						
					},
					{
						title: "Statistik",
						baseCls: "statisticsPanel",	
						autoScroll: true,
						items: [
							lineChartStatisticsPanel,			//Add the statisticsPanel
							pieChartStatisticsPanel
						]
					}
	    ]
    });

  	/*
  	 * Create the basic UI and implement the created panels
  	 */
	var viewport = new Ext.Viewport({									//Create the viewport
	  layout: "border",													//Choose the preexisting layout type "border"
	  items: [
			      //Header
				  {
					region: "north",									//Set the position of the map in the ExtJS border layout (reference for the viewport)
					baseCls: "headerRegion",							//Set the basic CSS reference name
					items: [headerGraphic, logoutPanel]					//Add header graphic + login area
				  },
				  
				  //Sidebar
				  //publicPanel
				  publicPanel,											//Add the public functions
				  		  
				  //administrationPanel
			  	  administrationPanel									//Add the admin functions
	  ]
	});
});

/*
*Function for clear all elements of editEventPanel
*/
function clearEditEventFormular(){
	Ext.getCmp("editName").setRawValue("");
	Ext.getCmp("editDescription").setRawValue("");
	Ext.getCmp("editFee").setRawValue("");
	Ext.getCmp("editLat").setRawValue("");
	Ext.getCmp("editLong").setRawValue("");
	Ext.getCmp("editTown").setRawValue("");
	Ext.getCmp("editPlz").setRawValue("");
	Ext.getCmp("editStreet").setRawValue("");
	Ext.getCmp("editNr").setRawValue("");
	Ext.getCmp("editLink").setRawValue("");
	Ext.getCmp("editKeywords").setRawValue("");
	Ext.getCmp("editCategories").setRawValue("");
	Ext.getCmp("editDate").setRawValue("");
	Ext.getCmp("editTime").setRawValue("");
	Ext.getDom("editVisibilityYes").checked=false;
	Ext.getDom("editVisibilityNo").checked=false;
}

function deleteEvent(idEvent){
	Ext.Ajax.request({																//Sending AJAX request
	  url: "../php/phpsql_deleteEvent.php",
	  method: "POST",          
      params: {
		idEvent:idEvent
	  },
	  success:function(){
		alert("Veranstaltung wurde erfolgreich gelöscht");
		clearEditEventFormular();
		Ext.getCmp("editableEvent").setRawValue("");
		editableEventsStore.load();
	  }
	});
}

/*
*Function to get event Information via Ajax Request
*/	
function getEventInformation(idEvent,test){
	Ext.Ajax.request({																//Sending AJAX request
	  url: "../php/phpsql_getEventInfo.php",
	  method: "POST",          
      params: {
		idEvent:idEvent
	  },
		success: function(response){													//Success function
		  	var xml = response.responseXML;											//Save resulting XML
		
		  	var event = xml.documentElement.getElementsByTagName("event");	
			
			/*
			*Write Elements from XML in Formular
			*/
			if(event[0].getElementsByTagName("name")[0].firstChild == null){
				var editName = "";
			}
			else{
				editName=event[0].getElementsByTagName("name")[0].firstChild.data;
				Ext.getCmp("editName").setRawValue(editName);
			}
			
			if(event[0].getElementsByTagName("description")[0].firstChild == null){
				var editDescription = "";
			}
			else{
				editDescription=event[0].getElementsByTagName("description")[0].firstChild.data;
				Ext.getCmp("editDescription").setRawValue(editDescription);
			}
			
			if(event[0].getElementsByTagName("fee")[0].firstChild == null){
				var editFee = "";
			}
			else{
				editFee=event[0].getElementsByTagName("fee")[0].firstChild.data;
				Ext.getCmp("editFee").setRawValue(editFee);
			}
			
			if(event[0].getElementsByTagName("lat")[0].firstChild == null){
				var editLat = "";
			}
			else{
				editLat=event[0].getElementsByTagName("lat")[0].firstChild.data;
				Ext.getCmp("editLat").setRawValue(editLat);
			}
			if(event[0].getElementsByTagName("long")[0].firstChild == null){
				var editLong = "";
			}
			else{
				editLong=event[0].getElementsByTagName("long")[0].firstChild.data;
				Ext.getCmp("editLong").setRawValue(editLong);
			}
			
			if(event[0].getElementsByTagName("town")[0].firstChild == null){
				var editTown = "";
			}
			else{
				editTown=event[0].getElementsByTagName("town")[0].firstChild.data;
				Ext.getCmp("editTown").setRawValue(editTown);
			}
			
			if(event[0].getElementsByTagName("plz")[0].firstChild == null){
				var editPlz = "";
			}
			else{
				editPlz=event[0].getElementsByTagName("plz")[0].firstChild.data;
				Ext.getCmp("editPlz").setRawValue(editPlz);
			}
			
			if(event[0].getElementsByTagName("street")[0].firstChild == null){
				var editStreet = "";
			}
			else{
				editStreet=event[0].getElementsByTagName("street")[0].firstChild.data;
				Ext.getCmp("editStreet").setRawValue(editStreet);
			}
			
			if(event[0].getElementsByTagName("nr")[0].firstChild == null){
				var editNr = "";
			}
			else{
				editNr=event[0].getElementsByTagName("nr")[0].firstChild.data;
				Ext.getCmp("editNr").setRawValue(editNr);
			}
			
			if(event[0].getElementsByTagName("link")[0].firstChild == null){
				var editLink = "";
			}
			else{
				editLink=event[0].getElementsByTagName("link")[0].firstChild.data;
				Ext.getCmp("editLink").setRawValue(editLink);
			}
			
			if(event[0].getElementsByTagName("keywords")[0].firstChild == null){
				var editKeywords = "";
			}
			else{
				editKeywords=event[0].getElementsByTagName("keywords")[0].firstChild.data;
				Ext.getCmp("editKeywords").setRawValue(editKeywords);
			}
			
			if(event[0].getElementsByTagName("categories")[0].firstChild == null){
				var editCategories = "";
			}
			else{
				editCategories=event[0].getElementsByTagName("categories")[0].firstChild.data;
				Ext.getCmp("editCategories").setRawValue(editCategories);
			}
			
			if(event[0].getElementsByTagName("date")[0].firstChild == null){
				var editDate = "";
			}
			else{
				editDate=event[0].getElementsByTagName("date")[0].firstChild.data;
				Ext.getCmp("editDate").setRawValue(editDate);
			}
			
			if(event[0].getElementsByTagName("time")[0].firstChild == null){
				var editTime = "";
			}
			else{
				editTime=event[0].getElementsByTagName("time")[0].firstChild.data;
				Ext.getCmp("editTime").setRawValue(editTime);
			}
			if(event[0].getElementsByTagName("visibility")[0].firstChild.data==1){
				Ext.getDom("editVisibilityYes").checked=true;
			}else{
				Ext.getDom("editVisibilityNo").checked=true;
			}

		}	
		  	

	});
}

function editEvent	(eventId,eventName,eventDescription,eventFee,eventLat,eventLong,eventTown,eventPlz,eventStreet,eventNr,
					editEventVisibility,eventDatetime, eventCategories,eventLink,eventKeyword){
	Ext.Ajax.request({																//Sending AJAX request
	  url: "../php/phpsql_editEvent.php",
	  method: "POST",          
      params: {
		eventId:eventId,
		eventName:eventName,
		eventDescription:eventDescription,
		eventFee:eventFee,
		eventLat:eventLat,
		eventLong:eventLong,
		eventTown:eventTown,
		eventPlz:eventPlz,
		eventStreet:eventStreet,
		eventNr:eventNr,
		eventVisibility:editEventVisibility,
		eventDatetime:eventDatetime,
		eventCategories:eventCategories,
		eventLink:eventLink,
		eventKeyword:eventKeyword	
	  },
	 success:function(){//if ajax request is successfull elements were cleared and store is reload
		alert("Veranstaltung wurde erfolgreich bearbeitet");
		clearEditEventFormular();
		Ext.getCmp("editableEvent").setRawValue("");
		editableEventsStore.load();
	  }
});
}  	
/*
 * Get events from MySQL-DB via AJAX request 
 * + Get attributes from the returnig XML 
 * + store informations in eventsArray 
 * + placeMarker on the map
 */
function getEvents(startdt, enddt, eventType, eventRadius,city){
	Ext.Ajax.request({																//Sending AJAX request
	  url: "../php/phpsql_getEvents.php",
	  method: "POST",          
      params: {																		//Parameters
    	  startdt: startdt,
    	  enddt: enddt,
    	  eventType: eventType,
    	  eventRadius: eventRadius,
		  city:city
      },
	  success: function(response){													//Success function
		  	markers.clearMarkers();													//Clear current makers from markers layers
		  	
		  	var xml = response.responseXML;											//Save resulting XML
		
		  	var events = xml.documentElement.getElementsByTagName("event");			//Get events from XML
		  	
		  	eventsArray = new Array();
		  		
		  	for (var i = 0; i < events.length; i++) {								//Get event attributes + store attributes in eventsArray
		  		if(events[i].getElementsByTagName("name")[0].firstChild == null){
					var name = "";
				}
				else{
					var name = events[i].getElementsByTagName("name")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("description")[0].firstChild == null){
					var description = "";
				}
				else{
					var description = events[i].getElementsByTagName("description")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("eventcategory")[0].firstChild == null){
					var eventcategory = "";
				}
				else{
					var eventcategory = events[i].getElementsByTagName("eventcategory")[0].firstChild.data;
				}
		  		if(events[i].getElementsByTagName("fee")[0].firstChild == null){
					var fee = "";
				}
				else{
					var fee = events[i].getElementsByTagName("fee")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("date")[0].firstChild == null){
					var date = "";
				}
				else{
					var date = events[i].getElementsByTagName("date")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("street")[0].firstChild == null){
					var street = "";
				}
				else{
					var street = events[i].getElementsByTagName("street")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("nr")[0].firstChild == null){
					var nr = "";
				}
				else{
					var nr = events[i].getElementsByTagName("nr")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("plz")[0].firstChild == null){
					var plz = "";
				}
				else{
					var plz = events[i].getElementsByTagName("plz")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("town")[0].firstChild == null){
					var town = "";
				}
				else{
					var town = events[i].getElementsByTagName("town")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("lat")[0].firstChild == null){
					var lat = "";
				}
				else{
					var lat = events[i].getElementsByTagName("lat")[0].firstChild.data;
				}
				if(events[i].getElementsByTagName("long")[0].firstChild == null){
					var long = "";
				}
				else{
					var long = events[i].getElementsByTagName("long")[0].firstChild.data;
				}
				
				var visibility = events[i].getElementsByTagName("visibility")[0].firstChild.data; 
				
		  		var html = "<h3>"+name+"</h3><br/>"+description+"<br/><br/>"+"<b>Eintritt: </b><br/>"+fee+"&euro;"+"<br/><br/><b>Adresse:</b><br/>"+street+" "+nr+"<br/>"+plz+" "+town;
		  		 
		  		eventsArray[i] = new Array();
				eventsArray[i][0] = name;
				eventsArray[i][1] = description;
				eventsArray[i][2] = eventcategory;
				eventsArray[i][3] = fee;
				eventsArray[i][4] = date;
				eventsArray[i][5] = street;
				eventsArray[i][6] = nr;
				eventsArray[i][7] = plz;
				eventsArray[i][8] = town;
				eventsArray[i][9] = lat;
				eventsArray[i][10] = long;
				eventsArray[i][11] = visibility;
				 
				placeMarker(lat, long, html, visibility);									//Call placeMarker function
		  	}
	      eventsStore.loadData(eventsArray);									//Manually load local data
      }
	});                                    
}
/*
 * This function places the marker to the map
 */
function placeMarker(lat, long, html, visibility){													
	var size = new OpenLayers.Size(21,25);
	if (visibility == 1){
		var icon = new OpenLayers.Icon("http://openlayers.org/api/img/marker-green.png", size);	
	}
	else{
		var icon = new OpenLayers.Icon("http://www.openlayers.org/dev/img/marker.png", size);	
	}	
	var location = new OpenLayers.LonLat(long, lat).transform(
			  	   new OpenLayers.Projection("EPSG:4326"), 		//Transform from WGS 1984
			  	   map.getProjectionObject() 					//To 'Spherical Mercator Projection' (EPSG:900913)
   	);
	var marker =  new OpenLayers.Marker(location, icon);		//Create new OpenLayers marker object
	addPopup(marker, location, html);							//Call addPopup function
	markers.addMarker(marker);									//Add the marker to the map
}

/*
 * This function adds a popup to the marker
 */
function addPopup(marker, location, html){
	var anchor = {													//Set zero point of the popup window 
		size: new OpenLayers.Size(0,0),
		offset: new OpenLayers.Pixel(0,0)	
	};
	
	marker.events.register("mousedown", marker, function(evt) { 	//Add mousedown listener			
		map.setCenter(location);									//Set mapcenter to marker location
	
		var popup = new OpenLayers.Popup.FramedCloud(				//Define Popup
			"event-info-popup",
            location, 
            null,
            html,
            anchor,
            true
	    );

		map.addPopup(popup);										//Add popup to the map
		OpenLayers.Event.stop(evt); 						
	});
}

/*
 * This function validates the form input of the newEventPanel based on the specified regex
 */
function validateNewEvent(form){

	//Regular expressions
	var emptyFieldExpression = /^$/;																					
	var noEmptyFieldExpression = /^[^"';]+$/;
	var emptyFieldProhibitedSignExpression=/(^$|^[^"';]+$)/;
	var dataExpression=/^$|(^[^"';]$jpe?g|gif|png)$/;
	var feeExpression = /^\$?[0-9]+((\.|\,)[0-9]{1,2})?$/;					
	var plzExpression=/^[0-9]{5}$/;
	var nrExpression=/(^$|^[1-9][0-9]?[0-9]?[0-9]?[a-zA-Z]?$)/;
	var timeExpression=/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
	var dateExpression=/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
	var countError=0;
	
	var errorString="In allen Feldern sind KEINE Anführungszeichen sowie Semikolons zu verwenden!\n";					//Define the error string
	
	//Test regular expression
	if (noEmptyFieldExpression.test(Ext.get("name").getValue())==false ){
		countError++;
		errorString=errorString.concat("Ein Veranstaltungsname muss angegeben werden!\n");
	}
	
	if (emptyFieldProhibitedSignExpression.test(Ext.get("description").getValue())==false ){
		countError++;
		errorString=errorString.concat("Falscheingabe in der Eventbeschreibung!\n");
	}
	
	if(emptyFieldExpression.test(Ext.get("fee").getValue())==false){		
		if (feeExpression.test(Ext.get("fee").getValue())==false){
			errorString=errorString.concat("Die Eingabe des Eintrittspreises ist nur als Zahl anzugeben!\n");
			countError++;						
		}					
	}
	
	//concat datetime value
	var feeNew = Ext.get("fee").getValue().replace(",",".");
	
	if (noEmptyFieldExpression.test(Ext.get("town").getValue())==false ){
		errorString=errorString.concat("Die Stadt in der die Veranstaltung stattfindet muss angegeben werden!\n");
		countError++;						
	}
	
	if (plzExpression.test(Ext.get("plz").getValue())==false ){
		errorString=errorString.concat("Eine Postleitzahl für den Ort der Veranstaltung muss angegeben werden!\n");
		countError++;						
	}
	
	if (emptyFieldProhibitedSignExpression.test(Ext.get("street").getValue())==false ){
		errorString=errorString.concat("Die Straße in der die Veranstaltung stattfindet muss angegeben werden!\n");
		countError++;						
	}
		
	if (nrExpression.test(Ext.get("nr").getValue())==false ){
		errorString=errorString.concat("Eine Hausnummer für den Ort der Veranstaltung muss angegeben werden!\n");
		countError++;		
	}
		
	if (dateExpression.test(Ext.get("date").getValue())==false || timeExpression.test(Ext.get("time").getValue())==false ){
		errorString=errorString.concat("Ein Datum und Zeit für die Veranstaltung muss im Format YYYY-MM-DD hh:min!\n");
		countError++;
			
	}
	else{
		dateNew=Ext.get("date").getValue().concat(" ");
	}
	
	if (noEmptyFieldExpression.test(Ext.get("allEventCategories").getValue())==false ){
		countError++;
		errorString=errorString.concat("Ein Veranstaltung muss einer Kategorie zugeordnet werden!\n");
	}
		
	if (emptyFieldProhibitedSignExpression.test(Ext.get("keywords").getValue())==false ){
		errorString=errorString.concat("Fehler im Schlagworte-Feld!\n");
		countError++;
	}
	
	if (emptyFieldProhibitedSignExpression.test(Ext.get("link").getValue())==false ){
		errorString=errorString.concat("Fehler im Website-Feld!\n");
		countError++;
	}
	
	if (noEmptyFieldExpression.test(Ext.get("culturalUser").getValue())==false ){
		errorString=errorString.concat("Fehler im Feld Kontaktperson!\n");
		countError++;
	}
	
	/*if (dataExpression.test(Ext.get("newEventUploadField").getValue())==false ){
		errorString=errorString.concat("Bitte nur Daten im Format png,jpg oder gif hochladen!\n");
		countError++;
	}*/
							
	if(countError>0){
		alert(errorString);	
	}
	else{	
		insertEvents(Ext.get("name").getValue(),Ext.get("description").getValue(),Ext.get("fee").getValue(),Ext.get("lat").getValue(),
		Ext.get("long").getValue(),Ext.get("town").getValue(),Ext.get("plz").getValue(),Ext.get("street").getValue(),Ext.get("nr").getValue(),
		eventVisibility,dateNew.concat(Ext.get("time").getValue()), Ext.get("allEventCategories").getValue(),Ext.get("link").getValue(),
		Ext.getCmp("culturalUser").getValue(),Ext.get("keywords").getValue());
		alert("Die Veranstaltung wurde eingetragen");
	}
}


/*
 * This function geocodes reverse using the Google Maps GC Engine
 * + Set Adress components in the newEventsForm
 */
function revGeocode(lat, long){
	var location = new google.maps.LatLng(lat, long);
	var geocoder = new google.maps.Geocoder();
	var address = geocoder.geocode( { "latLng": location}, function(results, status) {
		  if (status == google.maps.GeocoderStatus.OK) {
		  	//Get adress components
		  	var street = results[0].address_components[1].long_name;	
		  	var nr = results[0].address_components[0].long_name;
		  	var plz = results[0].address_components[5].long_name;
		  	var town = results[0].address_components[2].long_name;
		  	
		  	//Set adress components to the newEventPanel 
		  	Ext.getCmp("street").setValue(street);
		  	Ext.getCmp("nr").setValue(nr);
			Ext.getCmp("plz").setValue(plz);
		  	Ext.getCmp("town").setValue(town);
		   } 
		  else {
		    alert("Dem von Ihnen ausgewählten Punkt konnte keiner Adresse zugeordnet werden!");						//Error string
		  }
 	});
}



function insertEvents(name,description,fee,lat,lon,town,plz,street,nr,visibility,date, eventCategory,link,culturalUser,keyword)
{
	Ext.Ajax.request({											//Sending AJAX request
	  url: "../php/phpsql_insertEventsAdmin.php",
	  method: "POST",          
      params: {													//Parameters
    	  name: name,
    	  description: description,
    	  fee: fee,
    	  lat: lat,
    	  lon: lon,
    	  town: town,
		  plz: plz,
		  street:street,
		  nr:nr,
		  date: date,
		  visibility: visibility,		  
		  eventCategory: eventCategory,
		  link: link,
		  culturalUser: culturalUser,
		  keyword: keyword
      },
	  });
}

/*
 * Get statistic from MySQL-DB via AJAX request 
 * + Get attributes from the returnig XML 
 * + store informations in lineChartArray & in the
 *   lineChartStore
 */
function getLineChartStatistics(){
	Ext.Ajax.request({																//Sending AJAX request
	  	url: "../php/phpsql_getLineChartStatistics.php",
	  	method: "GET",          
	  	success: function(response){												//Success function
			var xml = response.responseXML;											//Save resulting XML
			var response = xml.documentElement.getElementsByTagName("month");
			
			lineChartArray = new Array();
			
			for (var i = 0; i < response.length; i++) {								
				lineChartArray[i] = new Array();
				lineChartArray[i][0] = response[i].id;
				lineChartArray[i][1] = response[i].firstChild.firstChild.data;
			}
			
			lineChartStore.loadData(lineChartArray);
		}
	});
}

/*
 * Get statistic from MySQL-DB via AJAX request 
 * + Get attributes from the returnig XML 
 * + store informations in pieChartArray & in the
 *   pieChartStore
 */
function getPieChartStatistics(){
	Ext.Ajax.request({																//Sending AJAX request
	  	url: "../php/phpsql_getPieChartStatistics.php",
	  	method: "GET",          
	  	success: function(response){												//Success function
			var xml = response.responseXML;											//Save resulting XML
			var response = xml.documentElement.getElementsByTagName("eventcategory");
			
			pieChartArray = new Array();
			
			for (var i = 0; i < response.length; i++) {								
				pieChartArray[i] = new Array();
				pieChartArray[i][0] = response[i].id;
				pieChartArray[i][1] = response[i].firstChild.firstChild.data;
			}
			
			pieChartStore.loadData(pieChartArray);
		}
	});
}

/*
 * This function initializes logout via an AJAX request
 */
function logoutRequest(){
	Ext.Ajax.request({									//Sending AJAX request
	  url: "../php/php_logout.php",
	  success: function() {								//Callback function
		  location.reload();							//Refresh page
	  },
	});
}
